<template>
  <div class="player" v-loading.lock="loading" element-loading-background="rgb(0, 0, 0)">
    <div id="player-con"></div>
    <!--  防挂机-人脸验证 -->
    <EduFaceVerify
      v-if="faceModalVisible"
      :visible.sync="faceModalVisible"
      scene_key="course_section"
      :scene_id="faceSceneId"
      :scene_type="faceSceneType"
      @cancel="onVerifySuccess"
    ></EduFaceVerify>

    <!--  防挂机-弹题 -->
    <prevent-popup
      v-if="popupVisible"
      :datas="playerData.onhook"
      :visible.sync="popupVisible"
      @click="onVerifySuccess"
    ></prevent-popup>

    <!--  防挂机-弹窗 -->
    <prevent-question
      v-if="questionVisible"
      :course_id="detailInfo.id"
      :course_type="detailInfo.course_type"
      :visible.sync="questionVisible"
      @click="onVerifySuccess"
    ></prevent-question>
  </div>
</template>
<script>
import { mapState, mapGetters } from 'vuex'
import eventVue from '../sectiobWatchEventVue.js'
import EduFaceVerify from '@/components/EduFaceVerify'
import preventQuestion from './preventQuestion'
import preventPopup from './preventPopup'
import CCH5BulletScreenComponent from '@/utils/CCH5BulletScreen.js'
import throttle from '@/utils/throttle.js'
export default {
  props: ['detailInfo'],
  components: {
    EduFaceVerify,
    preventQuestion,
    preventPopup
  },
  data() {
    return {
      player: null,

      autoplay: false, // 是否自动播放
      continue: false, // 播放完成后是否继续播放下一首，需定义@next事件
      controls: false, // 是否显示默认播放控件
      initialTime: 0, // 指定视频初始播放位置
      current: 0, // 当前进度(s)
      duration: 0, // 总时长(s)
      paused: true, // 是否处于暂停状态
      seek: false, // 是否处于拖动状态
      loading: true, //是否处于读取状态

      currentDuration: 0, // 记录学习时长

      previewEnd: false, // 试看状态
      previewDuration: 0, // 视频试看时长

      faceModalVisible: false, // 人脸验证弹出
      faceVerifyStart: false,
      faceVerifyEnd: true, // 人脸验证结束
      faceVerifyNumber: 0, // 还需要验证次数
      faceIntervalTime: 0, //见时间间隔
      faceNextVerifyTime: 0, // 下一次验证时间
      faceSceneType: 2, // 场景
      faceSceneId: 0, // 验证id
      faceShootStatus: false, // 续播状态

      playerData: {},

      questionVisible: false, // 弹题
      popupVisible: false, // 弹窗

      CCH5BulletScreen: null
    }
  },
  computed: {
    ...mapState({
      getCurrentPlayItem: state => state.course.currentPlayItem // 课时数据
    }),
    ...mapGetters({
      progressSwitch: 'projectSetting/getGlobProgress'
    }),
    sectionDataType() {
      return this.getCurrentPlayItem.section_data.data_type || 1
    },
    // 用户信息
    accountInfo() {
      return this.$store.getters['user/accountInfo']
    }
  },
  methods: {
    createPlayer(params) {
      let props = {
        autoStart: this.autoplay,
        width: '100%',
        height: '100%',
        playtype: 1,
        isShare: false, // 显示分享界面
        isShowUrlBtn: false, // 是否显示切换线路按钮
        isShowMoreBtn: false, // 是否显示右上角更多按钮
        forceShowVote: false, // 关闭强制显示答题器
        isShowExercise: false, // 是否显示课堂练习
        isShowVisitor: false, // 是否显示访客信息收集器
        isShowQuestions: false, // 是否显示问答
        isShowRightMenu: false, // 控制显示右侧菜单是否显示
        open_barrage: false, // 是否开启弹幕
        closeHistoryTime: 1, // 置是否关闭记忆播放功能。0，使用； 1，关闭
        parentNode: '#player-con',
        freeTimeTip: {
          msg: '观看完整视频,请先购买课程',
          linkText: '去购买',
          linkUrl: 'javascript:void(0)',
          target: '_self' // 在何处打开链接_blank 、 _self
        }, // 试看中文案提示
        freeTimeEndTip: {
          msg: '试看已结束',
          linkText: '去购买',
          linkUrl: 'javascript:void(0)',
          target: '_self' // 在何处打开链接_blank 、_self
        }, // 试看结束文案提示
        ...params
      }
      this.player = window.createCCH5Player(props)
    },
    setPlayerCallBack() {
      window.onCCH5PlayerLoaded = this.onPlayerLoaded
      window.on_CCH5player_ready = this.onPlayerReady
      window.on_CCH5player_play = this.onPlayerPlay
      window.on_CCH5player_pause = this.onPlayerPause
      window.on_CCH5player_ended = this.onPlayerEnded
      window.on_player_timeupdate = this.onPlayerTimeupdate
      window.on_player_seek = this.onPlayerSeek
    },
    // 播放下一个视频
    nextPlayer() {
      this.paused = true
      this.current = 0
      // this.autoplay = true;
      this.$store.commit('course/setCurrentPlayItem', {
        ...this.getCurrentPlayItem,
        ...this.playerData.next_position
      })
      if (this.player) {
        this.player.destroy() //销毁
      }
      if (this.getCurrentPlayItem.section_data.stock == 'bokecc') {
        this.getPlayerFile()
      }
    },
    /***
     * 播放器js文件加载完成的回调
     */
    onPlayerLoaded() {
      window.ccH5PlayerJsLoaded = true
    },
    /**
     * 播放器初始化完成即将播放时回调
     */
    onPlayerReady() {
      // dom插入版权声明
      const marqueeData = this.playerData.marquee

      // 防挂机
      if (!this.$util.isEmpty(marqueeData)) {
        // 版权信息
        if (marqueeData.copyright == 1) {
          let content = $(
            `<div class="ccH5copyrightBox"><div class="notice-content"><span class="notice-text">${marqueeData.copyright_content}</span></div></div>`
          )
          $('#player-con .ccH5playerBox').append(content)

          // 设置间隔
          let ccH5Html = $('#player-con .ccH5playerBox .ccH5copyrightBox')
          let noticeHtml = $('#player-con .ccH5playerBox .ccH5copyrightBox .notice-content')
          noticeHtml.on('animationiteration', () => {
            ccH5Html.css({
              opacity: 0
            })
            noticeHtml.css({
              animationPlayState: 'paused'
            })
            setTimeout(() => {
              ccH5Html.css({
                opacity: 1
              })
              noticeHtml.css({
                animationPlayState: 'running'
              })
            }, marqueeData.frequency * 1000)
          })
        }

        // 跑马灯
        if (this.sectionDataType == 1) {
          let marqueeContent = ''
          let name = ''
          let phone = ''
          if (marqueeData.username == 1) name = this.accountInfo.nick_name || ''
          if (marqueeData.phone == 1) phone = this.accountInfo.phone || ''
          marqueeContent = name + phone
          if (marqueeContent) {
            this.CCH5BulletScreen = new CCH5BulletScreenComponent(
              '#player-con .ccH5playerBox',
              marqueeContent,
              {
                fontSize: `${marqueeData.font_size}px`,
                color: this.$util.hexToRgba(marqueeData.font_color, marqueeData.font_opacity)
              },
              'top',
              marqueeData.frequency
            )
            this.CCH5BulletScreen && this.CCH5BulletScreen.ready()
          }
        }
      }

      if (this.initialTime > 0) {
        this.player.jumpToTime(this.initialTime)
        this.current = this.initialTime
      }

      setTimeout(() => {
        this.duration = this.player.getDuration() || this.getCurrentPlayItem.section_data.duration
        this.handleVerifyInit()
      }, 200)
    },
    /**
     * 播放时回调
     */
    onPlayerPlay() {
      this.paused = false
      this.onPreviewDurationPay() // 绑定试看点击事件
      this.CCH5BulletScreen && this.CCH5BulletScreen.playing()
    },
    /**
     * 暂停播放时回调
     */
    onPlayerPause() {
      this.paused = true
      this.CCH5BulletScreen && this.CCH5BulletScreen.pause()
    },
    /**
     * 播放结束时回调
     */
    onPlayerEnded() {
      this.handleAddLearning()
      // 顺序模式不跳转
      if (!this.playerData.course_lock == 1) {
        if (this.continue) {
          if (this.detailInfo.onhook_type == 3) {
            this.handleModalConfirm()
            this.faceSceneType = 1
            this.faceSceneId = this.playerData.next_position.id
            this.faceShootStatus = true
          } else {
            this.nextPlayer()
          }
        } else {
          this.paused = true
          this.current = 0
        }
      }
    },
    /**
     * 播放位置发生改变时回调
     * currentTime： 当前播放时间
     */
    onPlayerTimeupdate(currentTime) {
      if (!this.seek) {
        this.current = Math.floor(currentTime)
      }
      throttle(() => {
        this.currentDuration++
        if (this.currentDuration % 10 == 0) {
          this.handleAddLearning()
        }
        this.onVerifyTimeupdate(currentTime) // 人脸
        this.onPreviewDurationEnd(currentTime) // 处理试看
      }, 1000)
    },
    /**
     * 拖动或点击进度条改变播放进度时回调
     * prevTime: 进度变化前时间
     * currentTime: 视频进度变化后时间
     */
    onPlayerSeek(prevTime, currentTime) {},
    // 获取播放地址
    async getPlayerFile() {
      this.loading = true
      let playerProps = {}
      let class_id = this.detailInfo.course_type === 4 ? this.detailInfo.id : 0
      await this.$api.getCourseSectionFileurl(
        this.getCurrentPlayItem.course_id,
        this.getCurrentPlayItem.id,
        {
          class_id: class_id
        },
        res => {
          const { data } = res
          this.playerData = data

          // 音视频才能续播
          let sectionType = data.next_position?.section_data?.data_type
          let continuePlay = sectionType == 1 || sectionType == 2
          this.continue = !this.$util.isEmpty(data.next_position.position) && continuePlay

          // 人脸
          if (this.detailInfo.onhook_type == 3) {
            this.faceSceneId = this.getCurrentPlayItem.id
          }

          // 当前播放定位
          this.$store.dispatch('course/setCurrentPlayPosition', {
            ...data.curr_position
          })

          // 解锁模式,播放时保存已播放的id
          if (data.course_lock == 1) {
            this.$store.commit('course/setPlaySectionLock', this.getCurrentPlayItem.id)
          }
        }
      )
      this.handleAuditionTime() // 计算试听时长
      this.handleInitialTime()
      this.$api.getCourseSectionVideo(
        this.getCurrentPlayItem.course_id,
        this.getCurrentPlayItem.id,
        this.getCurrentPlayItem.section_data.stock,
        res => {
          const { data } = res

          playerProps = {
            ...playerProps,
            vid: data.videoid,
            siteid: data.userid
          }
          // 试看位置
          if (this.previewDuration > 0) {
            playerProps = {
              ...playerProps,
              freeTime: this.previewDuration
            }
          }
          // 指定视频指定位置
          if (this.initialTime > 0) {
            playerProps = {
              ...playerProps,
              watchStartTime: this.initialTime
            }
          }
          // 禁止拖动进度条
          if (this.progressSwitch == 1) {
            playerProps = {
              ...playerProps,
              progressbar_enable: 0 // 是否完全禁止进度条拖动,为0时禁止进度拖动，为1时允许拖动快进退
            }
          }

          this.player && this.player.destroy() // 销毁
          this.createPlayer(playerProps) // 创建播放器
          this.loading = false
        }
      )
    },
    // 计算试听时长
    handleAuditionTime() {
      this.previewEnd = false
      let buy = this.getCurrentPlayItem.is_buy
      if (this.$util.isDef(this.getCurrentPlayItem.is_buy) && buy == 0) {
        let audition = this.getCurrentPlayItem.audition || 0
        let duration = this.duration || this.getCurrentPlayItem.section_data.duration || 0
        this.previewDuration = Math.round(duration * (audition / 100))
      }
    },
    // 处理试看结束
    onPreviewDurationEnd(currentTime) {
      let isFullScreen = this.player && this.player.isFullScreen() // 获取当前屏幕全屏状态
      if (!this.previewEnd && this.previewDuration !== 0 && this.previewDuration < this.duration) {
        if (Math.floor(this.previewDuration) < currentTime) {
          if (isFullScreen) this.player.normalScreen() // 退出全屏播放
          this.previewEnd = true
          this.player.jumpToTime(this.previewDuration) // 跳转到某个时间点播放
          this.player.pause()
        }
      }
    },
    // 试看购买
    onPreviewDurationPay() {
      const _this = this
      let query = {
        cid: this.getCurrentPlayItem.course_id,
        redirect: `/course/${this.getCurrentPlayItem.course_id}`
      }
      $(function() {
        $('.CCH5playerContainer .ccH5FreeTimeTipBox a').click(function() {
          _this.$router.replace({ path: '/buy/course', query })
        })

        $('#player-con').on('click', '.ccH5TipBtn', function() {
          _this.$router.replace({ path: '/buy/course', query })
        })
      })
    },
    // 断点续播
    handleInitialTime() {
      let buy = this.getCurrentPlayItem.is_buy
      let time = this.getCurrentPlayItem.section_rate.current_time
      let duration = this.duration || this.getCurrentPlayItem.section_data.duration || 0
      if (this.$util.isDef(buy) && buy == 0) return
      this.initialTime = time > duration - 5 ? 0 : time
    },
    /* 验证 */
    handleVerifyInit() {
      this.popupVisible = false // 弹窗
      this.questionVisible = false // 弹题

      this.currentDuration = 0 // 当前播放时长

      this.faceSceneType = 2 // 人脸场景
      this.faceShootStatus = false // 人脸续播状态
      this.faceVerifyEnd = false // 验证结束
      this.faceNextVerifyTime = 0 // 下一次验证时间

      // 课时是否购买
      if (this.$util.isDef(this.getCurrentPlayItem.is_buy) && this.getCurrentPlayItem.is_buy == 0) {
        return
      }

      // 是否是视频
      if (
        this.$util.isDef(this.getCurrentPlayItem.section_data.data_type) &&
        this.getCurrentPlayItem.section_data.data_type != 1
      ) {
        return
      }

      // 是否开启验证
      if (this.detailInfo.onhook_type == 0) return

      if (this.detailInfo.onhook_type == 1) {
        const alertData = this.playerData.onhook
        this.faceVerifyNumber = alertData.alert_max_number // 验证次数
        this.faceIntervalTime = alertData.alert_time_interval * 60 //时间间隔
      } else if (this.detailInfo.onhook_type == 2) {
        const answerData = this.playerData.onhook_exam
        this.faceVerifyNumber = answerData.answer_max_number // 验证次数
        this.faceIntervalTime = answerData.answer_time_interval * 60 //时间间隔
      } else if (this.detailInfo.onhook_type == 3) {
        const faceData = this.playerData.face_data
        this.faceVerifyNumber = faceData.need_verify_number // 验证次数
        this.faceIntervalTime = faceData.verify_timespan * 60 // 时间间隔
      }
      this.nextVerifyTime()
    },
    // 计算下一次验证时间
    nextVerifyTime() {
      if (this.faceVerifyNumber > 0) {
        let time = this.currentDuration + this.faceIntervalTime
        this.faceNextVerifyTime = time
      } else {
        this.faceVerifyEnd = true
      }
    },
    // 播放时验证
    onVerifyTimeupdate(currentTime) {
      let isFullScreen = this.player && this.player.isFullScreen() // 获取当前屏幕全屏状态
      if (
        !this.faceVerifyEnd &&
        this.faceNextVerifyTime > 0 &&
        this.faceNextVerifyTime <= this.currentDuration
      ) {
        if (isFullScreen) this.player.normalScreen() // 退出全屏播放
        if (this.detailInfo.onhook_type == 1) {
          this.popupVisible = true
        } else if (this.detailInfo.onhook_type == 2) {
          this.questionVisible = true
        } else if (this.detailInfo.onhook_type == 3) {
          this.handleModalConfirm()
        }

        this.player.pause()
      }
    },
    // 去验证人脸
    handleModalConfirm() {
      if (this.faceVerifyStart) return
      this.faceVerifyStart = true
      // 验证人脸
      this.$messageBox
        .confirm('请进行人脸验证', {
          type: 'none',
          center: true,
          confirmButtonText: '去验证'
        })
        .then(() => {
          this.faceModalVisible = true
          this.faceVerifyStart = false
        })
        .catch(() => {
          this.faceVerifyStart = false
        })
    },
    // 验证成功
    onVerifySuccess() {
      // 续播
      if (this.faceShootStatus) {
        this.nextPlayer()
      } else {
        this.faceVerifyNumber-- // 还需要验证次数
        this.nextVerifyTime()
        this.player.play() // 视频播放
      }
    },
    // 添加学习记录
    handleAddLearning() {
      let buy = this.getCurrentPlayItem.is_buy
      if (this.$util.isDef(this.getCurrentPlayItem.is_buy) && buy == 0) return
      if (this.current <= 0) return
      this.$api.createCourseRecord({
        course_id: this.getCurrentPlayItem.course_id,
        section_id: this.getCurrentPlayItem.id,
        current_time: this.current
      })
    },
    // 生成随机数
    random(m, n) {
      m = m || 1
      n = n || 100
      if (m >= n) {
        n = m + 100
      }
      let w = n - m
      let num = Math.random() * w + m
      return Math.round(num)
    }
  },
  mounted() {
    this.getPlayerFile()
    this.setPlayerCallBack()
    eventVue.$on('sendSectionBybus', () => {
      this.loading = true
      if (this.getCurrentPlayItem.section_data.stock == 'bokecc') {
        this.getPlayerFile()
      }
    })
    // 点击右侧目录时暂停播放
    eventVue.$on('faceEntranceBybus', () => {
      this.player && this.player.pause()
    })
  },
  beforeDestroy() {
    this.player && this.player.destroy()
    this.player = null
  }
}
</script>
<style lang="scss" scoped>
.player {
  color: #fff;
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  background-color: #000;
  #player-con {
    width: 100%;
    height: 100%;
    ::v-deep .ccH5Poster img {
      height: 100%;
    }
  }
}
</style>
<style>
#player-con .ccH5copyrightBox {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  z-index: 999;
  padding: 5px 0;
  background: rgba(0, 0, 0, 0.2);
  overflow: hidden;
  display: flex;
}

#player-con .ccH5copyrightBox .notice-content {
  animation: cch5-loop-animation 10s linear infinite both;
  text-align: right;
  padding-left: 100%;
  display: flex;
  flex-wrap: nowrap;
  box-sizing: border-box;
}

#player-con .ccH5copyrightBox .notice-text {
  font-size: 13px;
  font-weight: 400;
  color: #ffffff;
  line-height: 18px;
  word-break: keep-all;
  white-space: nowrap;
}

#player-con .bullet-screen {
  position: absolute;
  white-space: nowrap;
  -webkit-animation: bullet 10s linear infinite;
  animation: bullet 10s linear infinite;
  right: 0;
  transform: translateX(100%);
  z-index: 1000;
}

@keyframes cch5-loop-animation {
  0% {
    transform: translate3d(0, 0, 0);
  }

  100% {
    transform: translate3d(-100%, 0, 0);
  }
}

@keyframes bullet {
  from {
    right: 0;
    transform: translateX(100%);
  }
  to {
    right: 100%;
    transform: translateX(-100%);
  }
}
</style>
